<template>
  <div class="app-container">
    <!--高级查询-->
    <div class="filter_container">
      <el-tabs v-model="params.status" type="card" @tab-click="handleFilter">
      <el-tab-pane name="0">
          <span slot="label"><i class="el-icon-s-order" /> 全部订单</span>
        </el-tab-pane>
        <el-tab-pane name="planning">
          <span slot="label"><i class="el-icon-s-order" /> 已创建</span>
        </el-tab-pane>
        <el-tab-pane name="planned">
          <span slot="label"><i class="el-icon-bank-card" /> 已计划</span>
        </el-tab-pane>
        <el-tab-pane name="departed">
          <span slot="label"><i class="el-icon-truck" /> 已出发</span>
        </el-tab-pane>
        <el-tab-pane name="received">
          <span slot="label"><i class="el-icon-refrigerator" /> 已收货</span>
        </el-tab-pane>
        <el-tab-pane name="canceled">
          <span slot="label"><i class="el-icon-circle-close" /> 已取消</span>
        </el-tab-pane>

      </el-tabs>
      <div class="filter_row">
        <el-form ref="form" :model="params" :inline="true" label-width="120px" size="mini">
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="订单号：">
                <el-input v-model="params.id" @keyup.enter.native="handleFilter" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="起运地：">
                <el-cascader
                  v-model="params.departureIdList"
                  :options="selects.locationList"
                  :props="{ expandTrigger: 'hover', label: 'locationName', value: 'id' }"
               clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="目的地：">
                <el-cascader
                  v-model="params.destinationIdList"
                  :options="selects.locationList"
                  :props="{ expandTrigger: 'hover', label: 'locationName', value: 'id' }"
               clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <!--操作按钮-->
    <div class="operation_container">
      <ul>
      <!--  <li><el-button v-waves type="primary" icon="el-icon-search" size="small" @click="handleFilter">查询</el-button></li>
        <li><el-button v-waves type="primary" icon="el-icon-circle-plus-outline" size="small" @click="handleAdd()">下新订单</el-button></li>
     <li><el-button v-if="params.status === `planning`" type="primary" icon="el-icon-upload2" size="small" @click="openCheckDialog">确认订单</el-button></li>
 <li><el-button v-if="params.status === `planned`" type="primary" icon="el-icon-upload2" size="small" @click="autoDispatch()">自动配载</el-button></li> -->

      </ul>
    </div>
    <!--栅格-->
    <div class="grid_container">
      <el-table
        ref="singleTable"
        v-loading="grid.loading"
        :data="page.records"
        element-loading-text="Loading"
        border
        stripe
        fit
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
       <el-table-column type="selection" align="center" width="40" />
              <el-table-column align="center" label="序" width="50">
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column type="expand">
                <template slot-scope="props" style="padding: 20px 50px;">
                  <el-table v-loading="grid.loading" :data="props.row.itemVoList" highlight-current-row>
                    <el-table-column label="明细" align="center" prop="materialDescribe" width="150px" />
                    <el-table-column label="子品牌" align="center" prop="vehicleName" width="150px" />
                    <el-table-column label="提车时间" align="center" prop="pickupStartDate" width="150px" />
                    <el-table-column label="提车人" align="center" prop="contactName" width="150px" />
                    <el-table-column label="SAP交货单" align="center" prop="pickupVoucherList" width="150px" />
                    <el-table-column label="库存地点描述" align="center" prop="pickUpWarehouseNo" width="150px" />
                    <el-table-column label="收车市" align="center" prop="pickupCity" width="150px" />
                    <el-table-column label="收车单位" align="center" prop="consigneeName" width="150px" />
                  </el-table>
                </template>
              </el-table-column>
        <!--      <el-table-column prop="purchaseOrderNo" label="订单号" align="center" show-overflow-tooltip width="200" />
       -->      <el-table-column label="订单号" align="center" show-overflow-tooltip width="150">
              <template slot-scope="scope">
                <el-button type="text" @click="handleView(scope.row)">{{ scope.row.purchaseOrderNo }}</el-button>
              </template>
            </el-table-column>
              <el-table-column label="订单状态" align="center" show-overflow-tooltip width="100">
                <template slot-scope="scope">
                  <span>{{ scope.row.status | purchaseOrderStatusFilter }}</span>
                </template>
              </el-table-column>
               <el-table-column prop="freightServiceType" label="运输方式" align="center" show-overflow-tooltip width="100" />
              <el-table-column prop="departureName" label="出发地" align="center" show-overflow-tooltip width="100" />
              <el-table-column prop="destinationName" label="到货地" align="center" show-overflow-tooltip width="150" />
              <el-table-column prop="consigneeName" label="提货人" align="center" show-overflow-tooltip width="100" />
              <el-table-column prop="consigneePhone" label="提货人电话" align="center" show-overflow-tooltip width="200" />
              <el-table-column prop="expectReceiptDate" label="要求发货时间" align="center" />
        <el-table-column label="操作" align="center" fixed="right" width="200">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
   <!--         <el-button v-if="scope.row.status === 'planning'" type="text" icon="el-icon-check" @click="openCheckDialog(scope.row)">确认订单</el-button>
  -->        </template>
        </el-table-column>
      </el-table>
    </div>
    <!--分页-->
    <div>
      <el-pagination
        v-show="page.total > 0"
        :current-page="page.currentPage"
        :page-sizes="page.pageSizes"
        :page-size="page.pageSize"
        :total="page.total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 对话框 -->
    <div class="dialog_container">
      <!--确认订单-->
      <el-dialog
        :title="checkDialog.title"
        :close-on-click-modal="false"
        :before-close="closeCheckDialog"
        :visible.sync="checkDialog.visible"
        width="500px"
      >
        <el-form :model="checkDialogData" label-position="right" label-width="120px" class="dialog_form">
          <el-form-item label="运单类型：" size="mini">
            <el-radio-group v-model="checkDialogData.freightOrderTypeNo">
              <el-radio v-for="item in selects.freightOrderTypeList" :key="item.key" :label="item.key">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="checkDialogData.freightOrderTypeNo === 'FTL'" label="车型：" size="mini">
            <el-select v-model="checkDialogData.ftlRequestVehicleType" filterable clearable>
              <el-option v-for="item in selects.vehicleModelList" :key="item.id" :label="item.vehicleModelDesc" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeCheckDialog()">取消</el-button>
          <el-button type="primary" @click="confirmCheckDialog()">保存</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="dialog_container">
          <el-dialog
            :title="dispatchDialog.title"
            :close-on-click-modal="false"
            :before-close="closeDispatchDialog"
            :visible.sync="dispatchDialog.visible"
            width="35%"
          >
            <el-form :model="dispatchDialogData" label-position="right" label-width="120px" class="dialog_form">
              <el-form-item size="mini" label="承运人：" prop="carrierName">
                <el-select v-model="dispatchDialogData.carrierId" @change="handleCarrierChange" clearable>
                  <el-option v-for="item in selects.carrierList" :key="item.id" :label="item.carrierName" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item size="mini" label="司机姓名：" prop="drivename">
                <el-select v-model="dispatchDialogData.vehicleInfoId" @change="handleVehicleInfoChange" clearable>
                  <el-option v-for="item in selects.vehicleInfoList" :key="item.id" :label="item.vehicleModelNo" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item size="mini" label="司机电话：" prop="cellNo">
                <el-input v-model="dispatchDialogData.cellNo" />
              </el-form-item>
              <el-form-item size="mini" label="车牌号：">
                <el-input v-model="dispatchDialogData.vehicleNo" />
              </el-form-item>
              <el-form-item size="mini" label="车(船)号：">
                <el-input v-model="dispatchDialogData.vehicleIdentity" />
              </el-form-item>
              <el-form-item size="mini" label="发布运输出价：">
                <el-input v-model="dispatchDialogData.publishDriverPrice" type="number" />
              </el-form-item>
              <el-form-item size="mini" label="要求车长：">
                <el-select v-model="dispatchDialogData.vehicleModelId" @change="handleVehicleModelChange" clearable>
                  <el-option v-for="item in selects.vehicleModelList" :key="item.id" :label="item.vehicleModelDesc" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="closeDispatchDialog()">取消</el-button>
              <el-button type="primary" @click="confirmDispatchDialog()">保存</el-button>
            </div>
          </el-dialog>
        </div>
  </div>
</template>

<script>
import waves from '@/directive/waves'
import appConfig from '@/config/AppConfig'
import appConstant from '@/constant/AppConstant'
import TreeUtils from '@/utils/TreeUtils'
import PurchaseOrderApi from '@/api/tms/TPoPurchaseOrderApi'
import LocationApi from '@/api/basic/LocationApi'
// import CarrierApi from '@/api/basic/CarrierApi'
// import VehicleInfoApi from '@/api/basic/VehicleInfoApi'
// import VehicleModelApi from '@/api/basic/VehicleModelApi'
export default {
  directives: {
    waves
  },
  filters: {
    purchaseOrderStatusFilter(item) {
      const values = appConstant.purchaseOrderStatusList.filter(value => value.key === item)
      if (values && values.length > 0) {
        return values[0].label
      } else {
        return ''
      }
    },
    freightSettleBasedonFilter(item) {
      const values = appConstant.settledBasedOnList.filter(value => value.key === item)
      if (values && values.length > 0) {
        return values[0].label
      } else {
        return ''
      }
    },
    freightBlancetypeFilter(item) {
      const values = appConstant.blanceTypeList.filter(value => value.key === item)
      if (values && values.length > 0) {
        return values[0].label
      } else {
        return ''
      }
    },
    freightPaymenttypeFilter(item) {
      const values = appConstant.paymentTypeList.filter(value => value.key === item)
      if (values && values.length > 0) {
        return values[0].label
      } else {
        return ''
      }
    }
  },
  data() {
    return {
      selects: {
        purchaseOrderStatusList: appConstant.purchaseOrderStatusList,
        freightOrderTypeList: appConstant.freightOrderTypeList,
        locationList: [],
       carrierList: [],
       vehicleInfoList: [],
       vehicleModelList: []
      },
      params: {
        departureIdList: [],
        destinationIdList: [],
        status: '0'
      },
      page: {
        current: 1,
        pageSize: 10,
        total: null,
        records: null
      },

      grid: {
        loading: true
      },
     multipleSelection: [],
     carrierSelectorVisible: false,
     vehicleInfoSelectorVisible: false,
     dispatchDialog: {
       title: '整车配载',
       visible: false
     },
     dispatchDialogData: {
       carrierId: '',
       vehicleInfoId: '',
       driveNo: '',
       drivename: '',
       freightItems: [],
       cellNo: '',
       vehicleNo: '',
       vehicleIdentity: '',
       vehicleModelDesc: ''
     },
      checkDialog: {
        title: '确认订单',
        visible: false
      },
      checkDialogData: {}
    }
  },
  created() {
    this.initloadData()
    this.loadSelects()
  },
  methods: {

    initloadData() {
      // 加载grid数据
      this.grid.loading = true
      const params = {
        ...this.params
      }
      params.status = "planning"
      PurchaseOrderApi.page(params, this.page).then(response => {
        this.page.total = response.data.total
        this.page.records = response.data.records
        this.grid.loading = false
      }, () => {
        this.grid.loading = false
      })
    },

     loadDispatchData() {
       CarrierApi.list().then(response => {
         this.selects.carrierList = response.data
         console.log(this.selects.carrierList)
       })
    // VehicleInfoApi.page({},{
    //   currentPage: 1,
    //   pageSize: 100 }).then(response => {
    //   this.selects.vehicleInfoList = response.data.rows
    //   console.log(this.selects.vehicleInfoList)
    // })
    // VehicleModelApi.list().then(response => {
    //   this.selects.vehicleModelList = response.data
    // })
    },
    loadData() {
      // 加载grid数据
      this.grid.loading = true
      const params = {
        ...this.params
      }
      if (params.status === '0') {
        params.status = undefined
      }
      PurchaseOrderApi.page(params, this.page).then(response => {
        this.page.total = response.data.total
        this.page.records = response.data.records
        this.grid.loading = false
      }, () => {
        this.grid.loading = false
      })
    },
    loadSelects() {
      LocationApi.list({leTreeLevel:2}).then(response => {
        this.selects.locationList = TreeUtils.list2Tree(response.data)
      })
      VehicleModelApi.list().then(response => {
        this.selects.vehicleModelList = response.data
      })
    },
    handleView(row) {
      this.$router.push({ path: '/purchaseOrder/purchaseOrderView/' + row.id })
    },
    handleAdd() {
      this.$router.push({ path: '/business/purchaseOrder/shipperForm' })
    },
    handleEdit(row) {
      this.$router.push({ path: '/business/purchaseOrder/form/' + row.id })
    },
    handleFilter() {
      this.page.currentPage = appConfig.page.currentPage
      // 转换起运地、目的地的查询参数
      if (this.params.departureIdList.length > 0) {
        this.params.departure = this.params.departureIdList.join(',')
      } else {
        this.params.departure = ''
      }
      if (this.params.destinationIdList.length > 0) {
        this.params.destination = this.params.destinationIdList.join(',')
      } else {
        this.params.destination = ''
      }
      this.loadData()
    },
    handleSizeChange(pageSize) {
      this.page.pageSize = pageSize
      this.loadData()
    },
    handleCurrentChange(currentPage) {
      this.page.currentPage = currentPage
      this.loadData()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
  openCheckDialog() {
    if (this.multipleSelection && this.multipleSelection.length) {
      this.checkDialog.visible = true
    } else {
      this.$message.warning('请选择数据')
    }
  },
    closeCheckDialog() {
      this.checkDialog = {
        title: '确认订单',
        visible: false
      }
      this.checkDialogData = {}
    },
  confirmCheckDialog() {
    // this.checkDialogData.purchaseOrderIdList = this.multipleSelection.map(row => row.id)
    this.checkDialogData.purchaseOrderSaveParams = this.multipleSelection
    PurchaseOrderApi.orderGenPickupDispatch(this.checkDialogData).then(() => {
      this.loadData()
      this.closeCheckDialog()
      this.$message.warning('订单确认成功')
    })
    }
  },
  openDispatchDialog() {
  if (this.multipleSelection && this.multipleSelection.length) {
        this.dispatchDialog.visible = true
        } else {
        this.$message.warning('请选择数据')
      }
      },
      closeDispatchDialog() {
        this.dispatchDialog = {
          title: '整车配载',
          visible: false
        }
        this.dispatchDialogData = {
          driveNo: '',
          drivename: '',
          cellNo: '',
          vehicleNo: '',
          vehicleIdentity: '',
          vehicleModelDesc: ''
        }
      },
      confirmDispatchDialog() {
         this.dispatchDialogData.freightItems = this.multipleSelection
        if (this.dispatchDialogData.driveNo !== '') {
          const params = {
            driver: this.dispatchDialogData.driveNo,
            orderId: this.dispatchDialogData.orderId,
            carrierNo: this.dispatchDialogData.carrierNo
          }
          FreightVehicleDispatchApi.createFtlDispatch(params).then(() => {
            this.$message.success('配载成功!')
            this.closeDispatchDialog()
          })
        } else {
          this.$message.warning('请选择承运人或司机')
        }
      },
 autoDispatch() {
          FreightVehicleDispatchApi.createAutoDispatch(params).then(() => {
            this.$message.success('配载成功!')

          })
        this.$router.push({ path: '/business/freightVehicleDispatch/publishlist' })
      },

      handleCarrierChange(id) {
        this.dispatchDialogData.carrierNo = undefined
        this.dispatchDialogData.carrierName = undefined
        CarrierApi.get(id).then(response => {
          this.dispatchDialogData.carrierNo = response.data.id
          this.dispatchDialogData.carrierName = response.data.carrierName
        })
      },
      handleVehicleInfoChange(id) {
        this.dispatchDialogData.driveNo = undefined
        this.dispatchDialogData.drivename = undefined
        this.dispatchDialogData.cellNo = undefined
        this.dispatchDialogData.vehicleNo = undefined
        this.dispatchDialogData.vehicleIdentity = undefined
        VehicleInfoApi.get(id).then(response => {
          this.dispatchDialogData.driveNo = response.data.driveNo
          this.dispatchDialogData.drivename = response.data.drivename
          this.dispatchDialogData.cellNo = response.data.cellNo
          this.dispatchDialogData.vehicleNo = response.data.vehicleNo
          this.dispatchDialogData.vehicleIdentity = response.data.vehicleIdentity
        })
      },
      handleVehicleModelChange(id) {
        this.dispatchDialogData.vehicleModelDesc = undefined
        VehicleModelApi.get(id).then(response => {
          this.dispatchDialogData.vehicleModelDesc = response.data.vehicleModelDesc
        })
      }
}
</script>
